package com.lee.controller;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@SuppressWarnings("all")
@RestController
public class ExcelDownController {


    @GetMapping("downLoadExcel")
    String downLoadExcel(HttpServletResponse response) {

        String[] title = {"poi", "name", "sex", "asd", "qwe", "tyu"};
        HSSFWorkbook workbook = new HSSFWorkbook();//创建Excel工作簿
        HSSFSheet sheet = workbook.createSheet();//创建一个工作表sheet
        HSSFRow row = sheet.createRow(0);//创建第一行
        HSSFCell cell = null;//创建单元格
        //插入第一行数据、id、name、sex
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 1);
        CellRangeAddress region2 = new CellRangeAddress(0, 0, 2, 3);
        CellRangeAddress region3 = new CellRangeAddress(0, 0, 4, 5);
        sheet.addMergedRegion(region);
        sheet.addMergedRegion(region2);
        sheet.addMergedRegion(region3);

        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);

        }
        //追加数据
        for (int i = 1; i < 10; i++) {
            HSSFRow nextRow = sheet.createRow(i);//创建第二行单元格
            HSSFCell cell2 = nextRow.createCell(0);
            cell2.setCellValue("a" + i);
            cell2 = nextRow.createCell(1);
            cell2.setCellValue("user" + i);
            cell2 = nextRow.createCell(2);
            cell2.setCellValue("男" + i);
            cell2 = nextRow.createCell(1);
            cell2.setCellValue("user" + i);
            cell2 = nextRow.createCell(2);
            cell2.setCellValue("男" + i);
            cell2 = nextRow.createCell(1);
            cell2.setCellValue("user" + i);
            cell2 = nextRow.createCell(2);
            cell2.setCellValue("男" + i);
        }
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=details.xls");
        response.setContentType("application/msexcel");
        try {
            ServletOutputStream stream = response.getOutputStream();
            workbook.write(stream);//写入流
            stream.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "success";
    }


}
